package com.iweb.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(value = "/*", initParams = {
        @WebInitParam(name = "code", value = "utf-8")
})
public class EncodeFilter implements Filter {

    private String code;

    // 获取指定的字符编码
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        code = filterConfig.getInitParameter("code");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 设定字符编码
        request.setCharacterEncoding(code);
        response.setCharacterEncoding(code);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // nothing
    }
}
